import os.path


def save_string_to_file(content, file_path, encoding='utf-8', overwrite=True):
    """
    将字符串内容保存到指定文件

    参数:
        content (str): 要保存的字符串内容
        file_path (str): 文件保存路径（相对或绝对路径）
        encoding (str): 文件编码格式，默认utf-8
        overwrite (bool): 是否覆盖已有文件，True为覆盖，False为追加

    返回:
        bool: 保存成功返回True，失败返回False
    """
    base_path = os.path.dirname(file_path)
    if not os.path.exists(base_path):
        os.makedirs(base_path, exist_ok=True)
    try:
        # 根据overwrite参数选择文件模式
        mode = 'w' if overwrite else 'a'

        # 使用with语句确保文件正确关闭
        with open(file_path, mode, encoding=encoding) as file:
            file.write(content)

        print(f"内容已成功{'覆盖' if overwrite else '追加'}到文件: {file_path}")
        return True

    except FileNotFoundError:
        print(f"错误: 找不到文件路径 {file_path}")
    except PermissionError:
        print(f"错误: 没有权限写入文件 {file_path}")
    except UnicodeEncodeError:
        print(f"错误: 内容包含无法用{encoding}编码的字符")
    except Exception as e:
        print(f"保存文件时发生错误: {str(e)}")

    return False
import subprocess
import json
import sys


def call_weidian_toc_api(output_file=None):
    """
    调用微店toc接口的函数，使用列表形式的curl命令参数

    参数:
        output_file (str, optional): 保存返回结果的文件路径，如果为None则不保存

    返回:
        tuple: (解析后的JSON数据, 错误信息)
    """
    # 将curl命令拆分为列表形式，每个参数作为独立元素
    curl_cmd = [
        'curl',
        'https://thor.weidian.com/help-center/repo.toc.get/1.0?param=%7B%22parentId%22%3A2963306%2C%22endpoint%22%3A%22pc%22%7D&wdtoken=6fac0d14&_=1754656806550',
        '-H', 'accept: application/json, */*',
        '-H', 'accept-language: zh-CN,zh;q=0.9',
        '-b',
        '__spider__visitorid=0a78fe9eb60f5b80; is_login=true; login_type=LOGIN_USER_TYPE_MASTER; login_source=LOGIN_USER_SOURCE_MASTER; uid=1978314980; duid=1978314980; sid=1616995651; smart_login_type=0; login_token=_EwWqqVIQFtUaMUa3nmffU0pTxOzSiRAfqRQTaTptPcleWfVbULaiSPz_BpbLGNDOdC9kMpbG0RaAKfQ4HsjPA2q0SAqcsDgb355mwlUul7qMOt7Fyd2NZrQUEzpECvBQ6kkgmJ-og8LD5B_w_r0tyq0yuoNmkkrJkXbbVF7NcIAt--M-l79aJejgeAXm5PCPBwUQrgu2cgo_XOn2h8E8-gQnCpkMn55xloSdd88WiVeWcaFRb7-6m82M4vbdvqpeNwZb2UQ7; hi_dxh=; hold=; cn_merchant=; Hm_lvt_f3b91484e26c0d850ada494bff4b469b=1754062222,1754125551; authAppId=; wdtoken=6fac0d14; __spider__sessionid=3b27fbd2acc7a818',
        '-H', 'origin: https://d.weidian.com',
        '-H', 'priority: u=1, i',
        '-H', 'referer: https://d.weidian.com/',
        '-H', 'sec-ch-ua: "Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
        '-H', 'sec-ch-ua-mobile: ?0',
        '-H', 'sec-ch-ua-platform: "Windows"',
        '-H', 'sec-fetch-dest: empty',
        '-H', 'sec-fetch-mode: cors',
        '-H', 'sec-fetch-site: same-site',
        '-H',
        'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36'
    ]

    try:
        # 执行命令
        result = subprocess.run(
            curl_cmd,  # 直接使用列表，无需shlex.split
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            check=False
        )

        json_data = json.loads(result.stdout)
        list = json_data['result']
        return list

    except json.JSONDecodeError as e:
        error_msg = f"JSON解析失败: {str(e)}"
        print(error_msg)
        print(f"原始响应内容: {result.stdout[:200]}...")
        return (None, error_msg)
    except subprocess.CalledProcessError as e:
        error_msg = f"命令执行失败: {e.stderr}"
        print(error_msg)
        return (None, error_msg)
    except Exception as e:
        error_msg = f"发生错误: {str(e)}"
        print(error_msg)
        return (None, error_msg)

def call_weidian_api(id):
    """
    调用微店API接口的函数，使用列表形式的curl命令参数

    参数:
        output_file (str, optional): 保存返回结果的文件路径，如果为None则不保存

    返回:
        tuple: (返回结果, 错误信息)
    """
    # 将curl命令拆分为列表形式，每个参数作为独立元素
    curl_cmd = [
        'curl',
        f'https://thor.weidian.com/help-center/repo.toc.list/1.0?param=%7B%22endpoint%22%3A%22pc%22%2C%22parentId%22%3A{id}%2C%22isPage%22%3Afalse%2C%22pageNum%22%3A1%2C%22pageSize%22%3A20%7D&wdtoken=6fac0d14&_=1754646482371',
        '-H', 'accept: application/json, */*',
        '-H', 'accept-language: zh-CN,zh;q=0.9',
        '-b',
        '__spider__visitorid=0a78fe9eb60f5b80; is_login=true; login_type=LOGIN_USER_TYPE_MASTER; login_source=LOGIN_USER_SOURCE_MASTER; uid=1978314980; duid=1978314980; sid=1616995651; smart_login_type=0; login_token=_EwWqqVIQFtUaMUa3nmffU0pTxOzSiRAfqRQTaTptPcleWfVbULaiSPz_BpbLGNDOdC9kMpbG0RaAKfQ4HsjPA2q0SAqcsDgb355mwlUul7qMOt7Fyd2NZrQUEzpECvBQ6kkgmJ-og8LD5B_w_r0tyq0yuoNmkkrJkXbbVF7NcIAt--M-l79aJejgeAXm5PCPBwUQrgu2cgo_XOn2h8E8-gQnCpkMn55xloSdd88WiVeWcaFRb7-6m82M4vbdvqpeNwZb2UQ7; hi_dxh=; hold=; cn_merchant=; Hm_lvt_f3b91484e26c0d850ada494bff4b469b=1754062222,1754125551; authAppId=; wdtoken=6fac0d14; __spider__sessionid=3b27fbd2acc7a818',
        '-H', 'origin: https://d.weidian.com',
        '-H', 'priority: u=1, i',
        '-H', 'referer: https://d.weidian.com/',
        '-H', 'sec-ch-ua: "Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
        '-H', 'sec-ch-ua-mobile: ?0',
        '-H', 'sec-ch-ua-platform: "Windows"',
        '-H', 'sec-fetch-dest: empty',
        '-H', 'sec-fetch-mode: cors',
        '-H', 'sec-fetch-site: same-site',
        '-H',
        'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36'
    ]

    try:
        # 执行命令（使用列表形式的参数更安全）
        result = subprocess.run(
            curl_cmd,  # 直接使用列表，无需shlex.split
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            check=False
        )


        json_data = json.loads(result.stdout)
        list = json_data['result']['list']
        return list

    except subprocess.CalledProcessError as e:
        error_msg = f"命令执行失败: {e.stderr}"
        print(error_msg)
        return (None, error_msg)
    except Exception as e:
        error_msg = f"发生错误: {str(e)}"
        print(error_msg)
        return (None, error_msg)

def run_curl_command(item, dir):
    # 拆分curl命令为列表形式（每个参数单独作为列表元素）
    # 注意：去掉CMD中的^转义符，直接按原始参数拆分
    curl_command = [
        "curl",
        f"https://thor.weidian.com/help-center/doc.get/1.0?param=%7B%22endpoint%22%3A%22pc%22%2C%22slug%22%3A%22{item['slug']}%22%7D&wdtoken=6fac0d14&_=1754646529679",
        "-H", "accept: application/json, */*",
        "-H", "accept-language: zh-CN,zh;q=0.9",
        "-b", "__spider__visitorid=0a78fe9eb60f5b80; is_login=true; login_type=LOGIN_USER_TYPE_MASTER; login_source=LOGIN_USER_SOURCE_MASTER; uid=1978314980; duid=1978314980; sid=1616995651; smart_login_type=0; login_token=_EwWqqVIQFtUaMUa3nmffU0pTxOzSiRAfqRQTaTptPcleWfVbULaiSPz_BpbLGNDOdC9kMpbG0RaAKfQ4HsjPA2q0SAqcsDgb355mwlUul7qMOt7Fyd2NZrQUEzpECvBQ6kkgmJ-og8LD5B_w_r0tyq0yuoNmkkrJkXbbVF7NcIAt--M-l79aJejgeAXm5PCPBwUQrgu2cgo_XOn2h8E8-gQnCpkMn55xloSdd88WiVeWcaFRb7-6m82M4vbdvqpeNwZb2UQ7; hi_dxh=; hold=; cn_merchant=; Hm_lvt_f3b91484e26c0d850ada494bff4b469b=1754062222,1754125551; authAppId=; wdtoken=6fac0d14; __spider__sessionid=3b27fbd2acc7a818",
        "-H", "origin: https://d.weidian.com",
        "-H", "priority: u=1, i",
        "-H", "referer: https://d.weidian.com/",  # 确保Referer头正确传递
        "-H", 'sec-ch-ua: "Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
        "-H", "sec-ch-ua-mobile: ?0",
        "-H", 'sec-ch-ua-platform: "Windows"',
        "-H", "sec-fetch-dest: empty",
        "-H", "sec-fetch-mode: cors",
        "-H", "sec-fetch-site: same-site",
        "-H", "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
    ]

    try:
        # 执行命令（不使用shell=True，直接传递列表参数）
        result = subprocess.run(
            curl_command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            check=False
        )

        # 解码输出（使用之前的多编码尝试方法）
        def decode_output(output_bytes):
            encodings = ['utf-8', 'gbk', 'gb2312']
            for encoding in encodings:
                try:
                    return output_bytes.decode(encoding).strip()
                except UnicodeDecodeError:
                    continue
            return f"无法解码: {output_bytes.hex()}"

        stdout = decode_output(result.stdout)
        # stderr = decode_output(result.stderr)

        json_data = json.loads(stdout)
        html = json_data['result']['bodyHtml']
        title = json_data['result']['title']
        save_string_to_file(html, f"{dir}/{title}.html")

    except Exception as e:
        print("11")
toc_list = call_weidian_toc_api()
for toc in toc_list:
    lei_list = call_weidian_api(toc['tocId'])
    for item in lei_list:
        run_curl_command(item, f"{toc['title']}")

